package com.ztom.v2;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author ZhangTao
 */
public class Code39SymmetricTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isSymmetric1(TreeNode root) {
        if (root == null) {
            return true;
        }
        return process(root.left, root.right);
    }

    public boolean process(TreeNode l, TreeNode r) {
        if (l == null && r == null) {
            return true;
        }
        if (l == null || r == null || l.val != r.val) {
            return false;
        }
        return process(l.left, r.right) && process(l.right, r.left);
    }


    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        queue.addLast(root.left);
        queue.addLast(root.right);
        while (!queue.isEmpty()) {
            TreeNode n1 = queue.pollFirst();
            TreeNode n2 = queue.pollFirst();
            if (n1 == null && n2 == null) {
                continue;
            }
            if (n1 == null || n2 == null || n1.val != n2.val) {
                return false;
            }
            queue.addFirst(n1.left);
            queue.addFirst(n2.right);
            queue.addFirst(n1.right);
            queue.addFirst(n2.left);
        }
        return true;
    }
}
